package com.liuyfly.leetcode.questions;

import com.liuyfly.leetcode.util.LeetcodeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * @author liuyangfang at 2022-08-30 13:57
 */
@Slf4j
public class Question0977 {

    /**
     * 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。 <br/>
     * <br/>
     * 链接： https://leetcode.cn/problems/squares-of-a-sorted-array
     */
    public static int[] sortedSquares(int[] nums) {
        int[] result = new int[nums.length];
        int minIndex = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] >= 0 && (nums[i] < nums[i + 1])) {
                break;
            }
            if (nums[i] < 0 && (nums[i] * nums[i] >= nums[i + 1] * nums[i + 1])) {
                minIndex++;
            } else if (nums[i] > 0 && (nums[i] * nums[i] > nums[i + 1] * nums[i + 1])) {
                minIndex++;
            }
        }
        System.out.println(minIndex);
        if (minIndex == 0) {
            for (int i = 0; i < nums.length; i++) {
                result[i] = nums[i] * nums[i];
            }
        } else if (minIndex == nums.length - 1) {
            for (int i = 0; i < nums.length; i++) {
                result[i] = nums[nums.length - i - 1] * nums[nums.length - i - 1];
            }
        } else {
            int left = minIndex - 1, right = minIndex + 1;
            result[0] = nums[minIndex] * nums[minIndex];
            for (int i = 1; i < result.length; i++) {
                log.info("left:{}, right:{}", left, right);
                if (left < 0) {
                    result[i] = nums[right] * nums[right];
                    right++;
                    continue;
                }
                if (right >= nums.length) {
                    result[i] = nums[left] * nums[left];
                    left--;
                    continue;
                }
                if (nums[left] * nums[left] <= nums[right] * nums[right]) {
                    result[i] = nums[left] * nums[left];
                    left--;
                } else {
                    result[i] = nums[right] * nums[right];
                    right++;
                }
            }
        }
        return result;
    }

    public static int[] sortedSquares2(int[] nums) {
        int[] result = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            result[i] = nums[i] * nums[i];
        }
        Arrays.sort(result);
        return result;
    }

    public static void main(String[] args) {
        int[] array = { -4, -4, 1 };
        int[] result = sortedSquares(array);
        LeetcodeUtil.printArray(result);
        int[] result2 = sortedSquares2(array);
        LeetcodeUtil.printArray(result2);
    }
}
